﻿using System;
using HNAlbum.Class;
using HNAlbum.Helper;
using HNAlbum.Logic.Entity;
using HNAlbum.Logic.Manager;
using HNAlbum.WebControl;
using System.Configuration;

namespace HNAlbum
{
    /// <summary>
    /// Login page
    /// </summary>
    public partial class Login : BasePage
    {
        #region Form events
        protected void Page_Init(object sender, EventArgs e)
        {
            RegisterJS("Login.js");
        }
        protected void Page_Load(object sender, EventArgs e) 
        {
            //Init welcome message and button
            string welcomeMsg = "Welcome to H&N Album";
            string welcomeBtn = "Take a Tour";
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["WelcomeMessage"])){
                welcomeMsg = ConfigurationManager.AppSettings["WelcomeMessage"];
            }
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["WelcomeButton"]))
            {
                welcomeBtn = ConfigurationManager.AppSettings["WelcomeButton"];
            }

            lblWelcome.Text = welcomeMsg;
            btnLoginAsGuest.Text = welcomeBtn;
        }
        /// <summary>
        /// Hanlde login
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Try get the user
            HNAlbumUser user = (new UserManager()).GetUser(txtUserName.Text);

            //Validate user
            if (user != null && user.ValidateLogin(txtUserName.Text, txtPassword.Text))
            {
                //Store login state
                CustomMasterPage.SessionCollection.User.IsAuthenticated = true;
                CustomMasterPage.SessionCollection.User.CurrentUser = user;

                //Navigate to home page
                Response.Redirect(Constant.PageURL.Home);
            }
            else
            {
                SetPageMessage("Invalid login. You will need to contact Hugh, sorry :)", PageMessage.MessageType.Error);
            }
        }
        /// <summary>
        /// Handle login as a guest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLoginAsGuest_Click(object sender, EventArgs e)
        {
            //Store login state
            CustomMasterPage.SessionCollection.User.IsAuthenticated = true;

            //Navigate to home page
            Response.Redirect(Constant.PageURL.Home);
        }
        #endregion
    }
}